package cc.linker.steplink.crm.commons.form;

import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.FormLoginDto;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.PRIVATE_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: CKQ
 * @DateTime: 2020/8/18 9:27
 * @Description: TODO
 */
@Slf4j
@Service
public class FormRequest {

    public static String FORM_LOGIN = "crm_form_login:customer_";

    @Value("${system.scrm.formAppId}")
    private String formAppId;
    @Value("${system.scrm.formUrl}")
    private String formUrl;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private HttpService httpService;

    /**
     * @Description：通用的接口请求
     * @DateTime：2020/8/18 9:36
     * @Params：active 方法
     * @Return：
     */
    public Object doRequest(String key, Map<String, Object> params, FormLoginDto formLoginDto) {
        InterfaceInfo interfaceInfo = ActiveConfig.getInterfaceInfo(key);
        if (interfaceInfo == null) {
            throw GlobalException.build("请求方法不能为空");
        }
        String authToken = "";
        if (formLoginDto != null) {
            formLoginDto.setAppId(formAppId);
            authToken = this.getFormAuthToken(formLoginDto);
            if (StringUtils.isEmpty(authToken)) {
                throw GlobalException.build("表单身份令牌获取失败");
            }
        } else {
            params.put("appId", formAppId);
        }
        Map<String, String> headerMap = this.initHeader(authToken);
        String result = "";
        String apiUrl = formUrl + interfaceInfo.getMethod();
        try {
            switch (interfaceInfo.getMode()) {
                case "get":
                    result = httpService.doGet(apiUrl, params, headerMap);
                    break;
                case "post":
                    result = httpService.doPost(apiUrl, JSON.toJSONString(params), headerMap);
                    break;
                case "delete":
                    result = httpService.doDelete(apiUrl, params, headerMap);
                    break;
                case "put":
                    result = httpService.doPut(apiUrl, JSON.toJSONString(params), headerMap);
                    break;
                default:
                    break;
            }
        }catch (Exception ex){
            LOGGER.error("请求中台表单系统失败---请求地址：" + JSON.toJSONString(interfaceInfo) + "请求参数:" + JSON.toJSONString(params),ex);
            throw GlobalException.build("请求失败，请重试！");
        }
        if (StringUtils.isEmpty(result)) {
            LOGGER.error("请求中台表单系统失败：" + JSON.toJSONString(interfaceInfo) + "请求参数:" + JSON.toJSONString(params));
            throw GlobalException.build("请求失败，请重试！");
        }
        Map resultMap = (Map) JSON.parse(result);
        if (resultMap != null) {
            if (resultMap.get("code").toString().equals("200")) {
                if (resultMap.containsKey("data")) {
                    return resultMap.get("data");
                } else {
                    return new HashMap<>();
                }
            } else if (resultMap.get("code").toString().equals("10022")) {
                stringRedisTemplate.delete(FORM_LOGIN + formLoginDto.getCustomerId());
                throw GlobalException.build(resultMap.get("请求失败，请重试！").toString());
            } else if (resultMap.get("code").toString().equals("404")) {
                if (resultMap.get("data") != null) {
                    Map dataMap = (Map) JSON.parse(resultMap.get("data").toString());
                    throw GlobalException.notFound(dataMap.get("belongId").toString());
                } else {
                    throw GlobalException.notFound();
                }
            } else {
                throw GlobalException.build(resultMap.get("msg").toString());
            }
        }
        return new HashMap();

    }

    public String exportData(HttpServletRequest request, FormLoginDto formLoginDto) {
        String formHT = this.getFormAuthToken(formLoginDto);
        return this.formUrl + request.getParameter("active") + "?formHT=" + formHT + "&" + request.getQueryString();
    }

    /**
     * @Description：登录表单系统并返回跳转地址
     * @DateTime：2020/8/6 17:49
     * @Params：
     * @Return：
     */
    private String getFormAuthToken(FormLoginDto formLoginDto) {
        String authToken = stringRedisTemplate.opsForValue().get(FORM_LOGIN + formLoginDto.getCustomerId());
        if (!StringUtils.isEmpty(authToken)) {
            stringRedisTemplate.opsForValue().set(FORM_LOGIN + formLoginDto.getCustomerId(), authToken, 1, TimeUnit.HOURS);
            return authToken;
        }
        try {
            formLoginDto.setAppId(formAppId);
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("appId", formAppId);
            headerMap.put("Content-Type", "application/json");
            try {
                String result = httpService.doPost(formUrl + "/form/getFormToken", JSON.toJSONString(formLoginDto), headerMap);
                if (StringUtils.isEmpty(result)) {
                    throw GlobalException.build("授权登录失败");
                }
                Map resultMap = (Map) JSON.parse(result);
                if (resultMap != null) {
                    if (resultMap.get("code").toString().equals("200") && resultMap.get("data") != null) {
                        Map dataMap = (Map) JSON.parse(resultMap.get("data").toString());
                        stringRedisTemplate.opsForValue().set(FORM_LOGIN + formLoginDto.getCustomerId(), dataMap.get("formHT").toString(), 1, TimeUnit.HOURS);
                        return dataMap.get("formHT").toString();
                    } else {
                        throw GlobalException.build(resultMap.get("msg").toString());
                    }
                }
            } catch (Exception ex) {
                throw GlobalException.build("授权登录失败");
            }
        } catch (Exception ex) {
            throw GlobalException.build("认证失败");
        }
        throw GlobalException.build("认证失败");
    }

    /**
     * @Description：生成header
     * @DateTime：2020/8/18 9:43
     * @Params：customerId 用户ID 传则需要组装authToken，不传则不用组装
     * @Return：
     */
    private Map<String, String> initHeader(String authToken) {
        Map<String, String> headerMap = new HashMap<>();
        if (StringUtils.isEmpty(authToken)) {
            headerMap.put("appId", formAppId);
        } else {
            headerMap.put("formHT", authToken);
        }
        headerMap.put("Content-Type", "application/json");
        return headerMap;
    }
}
